package com.weixing.mall.provider.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.annotation.SysLog;
import com.weixing.mall.core.enums.OperateEnum;
import com.weixing.mall.core.enums.SortOrderEnum;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.query.ActGoodsQuery;
import com.weixing.mall.provider.api.model.vo.ActivityProductVo;
import com.weixing.mall.provider.api.model.vo.GoodsDetailsVo;
import com.weixing.mall.provider.api.model.vo.GoodsPlaceVo;
import com.weixing.mall.provider.api.model.vo.ItemVo;
import com.weixing.mall.provider.erp.service.ErpService;
import com.weixing.mall.provider.model.domain.Goods;
import com.weixing.mall.provider.model.domain.Product;
import com.weixing.mall.provider.model.dto.*;
import com.weixing.mall.provider.model.enums.GoodsStateEnum;
import com.weixing.mall.provider.model.query.GoodsPlaceOrderQuery;
import com.weixing.mall.provider.model.query.GoodsQuery;
import com.weixing.mall.provider.model.vo.GoodsVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.support.excel.GoodsBasicImportData;
import com.weixing.mall.provider.support.excel.GoodsBasicImportDataListener;
import com.weixing.mall.provider.support.excel.TestImportData;
import com.weixing.mall.provider.support.excel.TestImportDataListener;
import com.weixing.mall.util.ListUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

/**
 * 后台商品模块
 *
 * @author wx
 * @date 2019/8/9 14:46
 * @since 1.0
 */
@RestController
@RequestMapping("goods")
public class GoodsController extends BaseController {

    @Autowired
    private IGoodsService goodsService;


    @Autowired
    private IProductService productService;

    @Autowired
    protected IGoodsPartitionService goodsPartitionService;

    @Autowired
    protected IGoodsSceneService goodsSceneService;
    @Autowired
    protected IGoodsPrintService goodsPrintService;
    @Autowired
    private ErpService erpService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IPhotoGalleryService photoGalleryService;
    @Autowired
    private IGoodsIntroService goodsIntroService;
    @Autowired
    private IGoodsImgService goodsImgService;

    /**
     * 查询商品
     * @param goodsQuery 查询参数
     * @return 商品列表
     */
    @GetMapping("")
    public Result<IPage<GoodsVo>> List(GoodsQuery goodsQuery) {
        return ResultUtil.success(goodsService.selectOfPage(initMpPage(), goodsQuery));
    }
    /**
     * 查询商品
     * @param goodsQuery 查询参数
     * @return 商品列表
     */
    @GetMapping("/exprot")
    @SysLog(type = OperateEnum.E,desp = "商品信息导出")
    public void exprotList(GoodsQuery goodsQuery, HttpServletResponse response) {
        try {
            goodsService.exprotList(goodsQuery,response);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询未进行SKU上传的商品
     * @param goodsQuery  查询参数
     * @return 商品列表
     */
    @ApiOperation(value = "查询SKU未上传的商品")
    @GetMapping("/selectNoSkuList")
    @NoNeedAccess
    public Result<IPage<GoodsVo>> selectNoSkuList(GoodsQuery goodsQuery) {
        return ResultUtil.success(goodsService.selectNoSkuList(initMpPage(), goodsQuery));
    }


    /**
     * 新增/修改
     *
     * @param goodsDto  参数
     * @return 结果
     */
    @PostMapping("save")
    @NoRepeatSubmit
    public Result save(GoodsDto goodsDto) {
        //判断这个商品货号是不是重复
//        if (goodsDto.getId() == null) {
//            Goods goods = goodsService.checkGoods(goodsDto.getGoodsSn(), goodsDto.getStyleNo());
//            if (goods != null) {
//                return ResultUtil.error("商品货号或者款号已经存在");
//            }
//        }else{
//            Goods goods = goodsService.checkGoods(goodsDto.getGoodsSn(), goodsDto.getStyleNo());
//            if(goods.getGoodsSn().equals(goodsDto.getGoodsSn())||goods.getStyleNo().equals(goodsDto.getStyleNo())){
//                return ResultUtil.error("商品货号或者款号已经存在");
//            }
//        }
        return ResultUtil.success(goodsService.save(goodsDto));
    }

    /**
     * 删除
     * @param ids id,多个英文逗号隔开
     * @return 结果
     */
    @PostMapping("delAll/{ids}")
    public Result delAll(@PathVariable int[] ids) {
        goodsService.delAll(ids);
        return ResultUtil.success();
    }

    /**
     * 上下架
     * @param dto 参数
     * @return 结果
     */
    @PostMapping("ChangeStatus")
    public Result ChangeStatus(@Validated GoodsChangeStatusDto dto) {
        goodsService.ChangeStatus(dto);
        Product product = new Product();
        product.setStatus(dto.getGoodsEnum().getValue());
        productService.update(product, new QueryWrapper<Product>().eq("goods_id", dto.getGoodsId()));
        return ResultUtil.success();
    }

    /**
     * 批量上下架
     * @param ids id,多个英文逗号隔开
     * @param flag 为2代表上架，3代表下架
     * @return 结果
     */
    @PostMapping("bathUpOrDown/{ids}")
    @NoNeedAccess
    public Result bathUpOrDown(@PathVariable Long[] ids, int flag) {
        List<Goods> goodsList = Lists.newArrayList();
        for (int i = 0; i < ids.length; i++) {
            Goods goods = new Goods();
            goods.setId(ids[i]);
            goods.setStatus(flag);
            goodsList.add(goods);
            Product product = new Product();
            product.setStatus(flag);
            productService.update(product, new QueryWrapper<Product>().eq("goods_id", ids[i]));
        }

            goodsService.updateBatchById(goodsList,ListUtil.SIZE);

        return ResultUtil.success();
    }

    /**
     * 整体上下架
     * @param goodsQuery 查询参数
     * @param flag 为2代表上架，3代表下架
     * @return 结果
     */
    @GetMapping("wholeUpOrDown")
    public Result wholeUpOrDown(GoodsQuery goodsQuery, int flag) {
        List<GoodsVo> tt = goodsService.selectNoPage(goodsQuery);
        List<Goods> goodsList = Lists.newArrayList();
        for (GoodsVo vo : tt) {
            Goods goods = new Goods();
            goods.setId(vo.getId());
            goods.setStatus(flag);
            goodsList.add(goods);
            Product product = new Product();
            product.setStatus(flag);
            productService.update(product, new QueryWrapper<Product>().eq("goods_id", vo.getId()));
        }
        if(flag==2){
            goodsService.updateBatchById(goodsList,ListUtil.SIZE);
        }
        return ResultUtil.success();
    }

    /**
     * 根据SKU进行上下架处理
     * @param skuUpOrDownDto SKU上下架状态
     * @return 结果
     */
    @PostMapping("skuUpOrDown")
    @NoNeedAccess
    public Result wholeUpOrDown(@Validated @RequestBody List<SkuUpOrDownDto> skuUpOrDownDto) {
        List<Goods> goodsList = Lists.newArrayList();
        List<Product> productList = Lists.newArrayList();
        if(ObjectUtil.isEmpty(skuUpOrDownDto)||ObjectUtil.isNull(skuUpOrDownDto)){
            return  ResultUtil.error("请选择其中一条记录");
        }
        for (SkuUpOrDownDto vo : skuUpOrDownDto) {
            /*只有上架，则good才会上架，其他保持不变*/
            if(vo.getGoodsEnum().getValue().equals(GoodsStateEnum.GROUNDING.getValue())){
                Goods goods = new Goods();
                goods.setId(vo.getGoodsId());
                goods.setStatus(vo.getGoodsEnum().getValue());
                goodsList.add(goods);
            }
            Product product = new Product();
            product.setId(vo.getProductId());
            product.setStatus(vo.getGoodsEnum().getValue());
            productList.add(product);
        }
        if(goodsList.size()!=0){
            goodsService.updateBatchById(goodsList,ListUtil.SIZE);
        }
       if(productList.size()!=0){
           productService.updateBatchById(productList,ListUtil.SIZE);
       }
        return ResultUtil.success();
    }

    /**
     * 根据商品id查询商品详情
     * @param goodsId 商品id
     * @return 商品详情
     */
    @PostMapping("selectDetails/{goodsId}")
    @NoNeedAccess
    public Result<GoodsDetailsVo> selectGoodsDetails(Long goodsId) {
        return ResultUtil.success(goodsService.selectById(goodsId));
    }


    /**
     * 根据分区,商品码，商品货号，商品名称查询
     * @param query 查询参数
     * @return 结果
     */
    @PostMapping("selectGoods")
    public Result<List<GoodsPlaceVo>> selectGoods(GoodsPlaceOrderQuery query) {
        return ResultUtil.success(goodsService.selectGoods(query));
    }

    /**
     * 根据分区,商品码，商品货号，商品名称查询商品（客服下单）
     * @param query  查询参数
     * @return 结果
     */
    @PostMapping("selectByGoodsInfo")
    public Result<IPage<GoodsPlaceVo>> selectByGoodsInfo(GoodsPlaceOrderQuery query) {
        return ResultUtil.success(goodsService.selectByGoodsInfo(initMpPage(), query));
    }


    /**
     * 调拨单导入,1代表调拨单，2代表入库
     * @param file      文件
     * @param depotId   仓库id
     * @return 结果
     */
    @PostMapping("importExcelGoods")
    public Result<List<ItemVo>> importExcelGoods(MultipartFile file, Long depotId) {
        List<ItemVo> result = goodsService.importByOrderSn(file, depotId);
        return ResultUtil.success(result);
    }

    /**
     * 初始化入库批量导入
     * @param file  文件
     * @return  结果
     */
    @PostMapping("importExcelInDepot")
    public Result< List<ItemVo>> importExcelInDepot(MultipartFile file) {
        List<ItemVo> result = goodsService.importExcelInDepot(file);
        return ResultUtil.success(result);
    }

    /**
     * 活动模块-查询商品
     * @param goodsQuery  查询参数
     * @return  结果
     */
    @GetMapping("findActProductVo")
    public Result<IPage<ActivityProductVo>> findActProductVo(ActGoodsQuery goodsQuery) {
        IPage pageInfo = productService.findActProductVo(initMpPage(), goodsQuery);
        return ResultUtil.success(pageInfo);
    }

    /**
     * 商品模块-商品码打印
     * @param ids        商品id
     * @param number     数量
     * @return   请求结果
     */
    @PostMapping("codePrint/{ids}")    @ApiOperation(value = "")
    public Result codePrint(@PathVariable Long[] ids, @RequestParam(value = "number", defaultValue = "0") int number) {
        SysAuth auth = AuthUtil.getSysExt();
        goodsPrintService.codePrint(ids, auth);
        return ResultUtil.success();
    }

    /**
     * 商品模块-商品码使用payLoad的传参方式
     * @param ids 商品id
     * @return  结果
     */
    @PostMapping("codePrint")
    public Result codePrint(@RequestBody Long[] ids) {
        SysAuth auth = AuthUtil.getSysExt();
        goodsPrintService.codePrint(ids, auth);
        return ResultUtil.success();
    }

    /**
     * 商品模块-商品码打印-2020-10-27
     * @param ids  参数
     * @return  结果
     */
    @PostMapping("codePrint2")
    public Result codePrint2(GoodsPrintIdsDto ids) {
        SysAuth auth = AuthUtil.getSysExt();
        if (ids != null && ids.getIds() != null) {
            goodsPrintService.codePrint(ids.getIds(), auth);
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }

    /**
     * 商品模块-商品码打印  新
     * @param goodPrintList  参数
     * @return 返回结果
     */
    @PostMapping("codePrints")
    public Result codePrints(@RequestBody List<GoodsPrintDto> goodPrintList) {
        SysAuth auth = AuthUtil.getSysExt();
        goodsPrintService.codePrint(goodPrintList, auth);
        return ResultUtil.success();
    }

    /**
     * 商品模块-商品码打印-颜色尺码选择列表
     * @param ids  id,多个使用英文逗号隔开
     * @return  结果
     */
    @PostMapping("selectProduct/{ids}")
    public Result<List<Product>> selectProduct(@PathVariable Long[] ids) {
        return ResultUtil.success(productService.selectByGoodsIds(ids));
    }

    /**
     * 新增商品-excel导入
     * @param file 导入文件
     * @return 结果
     */
    @PostMapping("import")
    public Result importExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), GoodsBasicImportData.class, new GoodsBasicImportDataListener(goodsService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("Excel导入失败");
        }
        return ResultUtil.success();
    }

    /**
     * 商品排序
     *
     * @param sortOrderEnum  排序
     * @return 结果
     */
    @GetMapping("sortGoods")
    public Result sortGoods(SortOrderEnum sortOrderEnum) {
        goodsService.sortGoods(sortOrderEnum.getValue());
        return ResultUtil.success();
    }


    /**
     * 商品排序修改
     *
     * @param id     商品id
     * @param sort   排序
     * @return  执行结果
     */
    @GetMapping("chgSort/{id}/{sort}")
    public Result chgSort(@PathVariable Long id, @PathVariable Long sort) {
        Goods goods = goodsService.getById(id);
        goods.setOrderNo(sort);
        goodsService.updateById(goods);
        return ResultUtil.success();
    }


    /**
     * Erp同步
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @return  执行结果
     */
    @GetMapping("erpSync")
    @NoNeedAccess
    public Result erpSync(String startTime, String endTime) {
        erpService.syncAllGoodFromErp(startTime, endTime);
        return ResultUtil.success();
    }

    /**
     * 新增商品测试-excel导入测试误用
     * @param file  导入文件
     * @return  执行结果
     */
    @PostMapping("importtest")
    @NoNeedAccess
    public Result importExceltest(MultipartFile file) {

        try {

            EasyExcel.read(file.getInputStream(), TestImportData.class, new TestImportDataListener(photoGalleryService, goodsService, goodsIntroService, categoryService, goodsImgService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("Excel导入失败");
        }
        return ResultUtil.success();
    }

}
